// index.js
var common = require('../../utils/userstatus');
var util = require('../../utils/util');
Page({
  data: {
    noonTip: "",
    userInfo: {
      profileImagePath: util.defaultAvatarUrl,
      username: ""
    },
    appInstance: "",
    addUserId: ""
  },
  onLoad(options) {
    console.log(options)
    this.data.addUserId = options.id;
    this.redirectToIndex(false);
    var appInstance = getApp();
    this.data.appInstance = appInstance;
    //老用户直接登录
    const token = wx.getStorageSync('accessToken');
    if (token) {} else {
      //如果有此标志，代表不需要自动登记
      var autoLogin = wx.getStorageSync('autoLogin');
      if (autoLogin) {

      } else {
        //直接登录
        this.directLoginButtonTap();
      }
    }
    // const date = new Date();
    // const hour = date.getHours();
    // var noonTip;
    // if (hour >= 0 && hour < 12) {
    //   noonTip = '上午好';
    // } else if (hour === 12) {
    //   noonTip = '中午好';
    // } else if (hour > 12 && hour < 18) {
    //   noonTip = '下午好';
    // } else {
    //   noonTip = '晚上好';
    // }
    // this.setData({
    //   noonTip: noonTip
    // })

  },
  onChooseAvatar(e) {
    console.log(e)
    this.setData({
      'userInfo.profileImagePath': e.detail.avatarUrl
    })
  },
  selectionchange(e) {
    this.data.userInfo.username = e.detail.value;
  },
  selectionPhoneNumberchange(e) {
    this.data.userInfo.phoneNumber = e.detail.value;
  },
  getPhoneNumber(e) {
    wx.showLoading();
    console.log(e.detail.code) // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno)
    var userInfo = this.data.userInfo;
    console.log(userInfo)

    var code = e.detail.code;
    if (code) {
      // if (!userInfo.username ||
      //   (userInfo.username && util.isBlank(userInfo.username))) {
      //   wx.hideLoading();
      //   wx.showToast({
      //     title: '用户名不能为空',
      //     icon: 'error',
      //     duration: 2000
      //   })
      //   return;
      // }
      var url = '/applet/getPhoneNumberFree';
      util.postRequest(url, {
        code: code
      }, (data) => {
        if (data.code == 2000) {
          var phoneNumber = data.data.phoneNumber;
          if (phoneNumber) {
            this.data.userInfo.phoneNumber = phoneNumber;
            this.loginFirst();
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '登录失败',
              icon: 'error',
              duration: 2000
            })
          }
        } else {

          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            icon: 'error',
            duration: 2000
          })
        }
      }, error => {
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'error',
          duration: 2000
        })

      })
    } else {
      wx.hideLoading();
    }
  },
  redirectToIndex(close) {
    const token = wx.getStorageSync('accessToken');
    if (token) {
      wx.setStorageSync('sharedId', this.data.addUserId)
      wx.switchTab({
        url: '/pages/index/index',
        complete: (com) => {
          if (close) {
            wx.hideLoading();
          }
        }
      })
    }
  },
  loginFirst() {
    wx.showLoading({
      title: '登录中...',
    });
    var userInfo = this.data.userInfo;
    var phoneNumber = userInfo.phoneNumber;
    var profileImagePath = userInfo.profileImagePath;
    var defaultImageFlag = false;
    if (profileImagePath && profileImagePath === util.defaultAvatarUrl) {
      profileImagePath = util.backServerUrl + util.defaultServerAvatarUrl;
      defaultImageFlag = true;
    }
    console.log(profileImagePath)
    var that = this;
    if (profileImagePath) {
      if (profileImagePath.startsWith("wxfile:")) {
        wx.login({
          success(res) {
            if (res.code) {
              that.backServerLogin(res.code, userInfo, defaultImageFlag)
            } else {
              wx.hideLoading();
              wx.showToast({
                title: '错误,请重试!',
                icon: 'error',
                duration: 2000
              })
            }
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '错误,请重试!',
              icon: 'error',
              duration: 2000
            })
          }
        })
      } else {
        util.downloadFile(
          profileImagePath,
          (res) => {
            wx.hideLoading();
            if (res.statusCode === 200) {
              userInfo.profileImagePath = res.tempFilePath
              wx.login({
                success(res) {
                  if (res.code) {
                    that.backServerLogin(res.code, userInfo, defaultImageFlag)
                  } else {
                    wx.hideLoading();
                    wx.showToast({
                      title: '错误,请重试!',
                      icon: 'error',
                      duration: 2000
                    })
                  }
                },
                fail: () => {
                  wx.hideLoading();
                  wx.showToast({
                    title: '错误,请重试!',
                    icon: 'error',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.showToast({
                title: '头像处理失败!',
                icon: 'error',
                duration: 2000
              })
              return;
            }
          },
          (error) => {
            wx.hideLoading();
            wx.showToast({
              title: '头像处理失败!',
              icon: 'error',
              duration: 2000
            })
            return;
          })
      }

    } else {
      wx.hideLoading();
      wx.showToast({
        title: '请选择头像',
        icon: 'error',
        duration: 2000
      })
      return;
    }


  },
  backServerLogin(code, userInfo, defaultImageFlag) {
    var url = '/applet/loginFirst';
    util.uploadFile(
      url,
      this.data.userInfo.profileImagePath, {
        username: this.data.userInfo.username,
        code: code,
        phoneNumber: this.data.userInfo.phoneNumber
      },
      (suc) => {
        var data = JSON.parse(suc);
        wx.hideLoading();
        //已经登录
        if (data.code === 2100) {
          this.directLogin({
            id: data.data.id,
            username: data.data.username,
            profileImagePath: data.data.profileImagePath,
            phoneNumber: data.data.phoneNumber,
            defaultImageFlag: defaultImageFlag
          });
        } else if (data.code === 2000) {
          this.loginSuccess(data);
        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '错误,请重试!',
          icon: 'error',
          duration: 2000
        })
      }
    )
  },
  loginSuccess(data) {
    var that = this;
    var userInfo = data.data
    var userStatusStr = userInfo.userStatusStr;
    if (userStatusStr === 'null' || !userStatusStr) {
      userInfo.userStatusStr = common.userStatus[0].value;
    }
    if (userInfo.profileImagePath &&
      !userInfo.profileImagePath.includes("http")) {
      userInfo.profileImagePath = util.backServerUrl + userInfo.profileImagePath;
    }
    if (userInfo.profileImagePath == null) {
      userInfo.profileImagePath = "/images/index/youkongma.jpg"
    }
    wx.setStorageSync('userInfo', userInfo);
    wx.setStorageSync('accessToken', data.data.accessToken);
    wx.setStorageSync('refreshToken', data.data.refreshToken);
    wx.showLoading({
      title: '登录成功，跳转中...',
    })
    that.redirectToIndex(true);
  },
  directLogin(data) {
    console.log(data)
    wx.showLoading();
    var id = data.id;
    var reqData = {};
    if (id) {
      reqData.username = data.username;
      reqData.profileImagePath = data.profileImagePath;
      reqData.id = id;
      reqData.phoneNumber = data.phoneNumber;
      reqData.defaultImageFlag = data.defaultImageFlag;
    } else {
      reqData.code = data.code;
    }
    var url = '/applet/login';
    util.postRequest(
      url,
      reqData,
      (data) => {
        wx.hideLoading();
        if (data.code == 2000) {
          this.loginSuccess(data);
        } else if (data.code == 2101) {
          wx.showToast({
            title: '请先注册',
            icon: 'error',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '异常',
            icon: 'error',
            duration: 2000
          })
        }
      },
      (error) => {
        console.log(error)
        wx.hideLoading();
        wx.showToast({
          title: '异常',
          icon: 'error',
          duration: 2000
        })
      })
  },
  directLoginButtonTap() {
    var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          that.directLogin({
            code: res.code
          })
        } else {
          wx.hideLoading();
          // wx.showToast({
          //   title: '错误,请重试!',
          //   icon: 'error',
          //   duration: 2000
          // })
        }
      },
      fail: () => {
        wx.hideLoading();
        // wx.showToast({
        //   title: '错误,请重试!',
        //   icon: 'error',
        //   duration: 2000
        // })
      }
    })
  },
  quit() {
    wx.exitMiniProgram();
  }
})